#include "tlv_parser.h"

TLVParser::TLVParser(const TLVBuffer& buffer) : buffer_(buffer) {}

bool TLVParser::parse() {
    size_t offset = 0;
    while (offset + 4 <= buffer_.size()) {
        TLV item;
        if (!buffer_.readTLV(offset, item)) break;

        classified_[item.type].push_back(item);
        offset += 4 + item.length;
    }
    return !classified_.empty();
}

std::vector<TLV> TLVParser::getByType(TLVType type) const {
    auto it = classified_.find(type);
    if (it != classified_.end()) return it->second;
    return {};
}

std::optional<TLV> TLVParser::getFirst(TLVType type) const {
    auto it = classified_.find(type);
    if (it != classified_.end() && !it->second.empty()) return it->second.front();
    return std::nullopt;
}
